package org.yxing.palpalgps.activity;

import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.yxing.palpalgps.ActionBar.OnActionBarListener;
import org.yxing.palpalgps.BaseActivity;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.adapter.InterestAdapter;
import org.yxing.palpalgps.adapter.SchoolAdapter;
import org.yxing.palpalgps.http.AsyncRequest;
import org.yxing.palpalgps.http.AsyncRequest.FetchListener;
import org.yxing.palpalgps.models.Interest;
import org.yxing.palpalgps.models.School;
import org.yxing.palpalgps.oauth.OAuth;
import org.yxing.palpalgps.utils.Helper;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

public class GroupsActivity extends BaseActivity implements OnActionBarListener, OnItemClickListener, OnItemLongClickListener {
    private static final String TAG = GroupsActivity.class.getSimpleName();
    /**
     * 已加入兴趣 Url
     */
    private static final String URL_FETCH = "group/my";
    
    private static final String URL_DELETE = "group/quit";
    
    /**
     * is reload data, after add interest, data while be reload
     */
    private boolean isReloadData = false;
    
    /**
     * HomeActivity
     */
    private HomeActivity mHomeActivity;
    
    private ListView schoolListView;
    private ListView interestListView;
    
    private AsyncRequest mAsyncRequest;
    private SchoolAdapter mSchoolAdapter;
    private InterestAdapter mInterestAdapter;
    
    /**
     * on create
     */
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.group);
        
        mHomeActivity = (HomeActivity) getParent();
        //set title
//        mHomeActivity.setTitle("Group");
        
        //school
        schoolListView = (ListView) findViewById(R.id.schoolListView);
        mSchoolAdapter = new SchoolAdapter(this);
        schoolListView.setAdapter(mSchoolAdapter);
        
        //interest
        interestListView = (ListView) findViewById(R.id.interestListView);
        mInterestAdapter = new InterestAdapter(this);
        interestListView.setAdapter(mInterestAdapter);
        
        //set click listener
        schoolListView.setOnItemClickListener(this);
        schoolListView.setOnItemLongClickListener(this);
        interestListView.setOnItemClickListener(this);
        interestListView.setOnItemLongClickListener(this);
        
        mAsyncRequest = new AsyncRequest(this);
        
        fetchData();
    }
    
    public void onResume() {
        super.onResume();
        mHomeActivity.getActionBar().setOnActionBarListener(this);
        if (isReloadData) 
            fetchData();
    }
    
    /**
     * fetch data
     */
    public void fetchData() {
//        Log.v(TAG, "fetchData");
        isReloadData = false;
        String url = Helper.getAppUrl(URL_FETCH);
        mAsyncRequest.fetch(url, new FetchListener() {
            
            public void onError(int code, String msg) {
                Log.w(TAG, code + msg);
            }
            
            public void onComplete(JSONObject response) {
//                Log.v(TAG, "onComplete");
                try {
                    mSchoolAdapter.clear();
                    
                    JSONObject result = response.getJSONObject("result");
                    
                    JSONArray schools = result.getJSONArray("schools");
                    for (int i = 0; i < schools.length(); i ++) {
                        JSONObject json = schools.getJSONObject(i);
                        School s = new School(json.getInt("sid"), json.getString("name"));
                        mSchoolAdapter.addItem(s);
                    }
                    
                    JSONArray interests = result.getJSONArray("groups");
                    mInterestAdapter.setData(interests);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            return false;
        return super.onKeyUp(keyCode, event);
    }

    /**
     * action bar item click
     */
    public void onActionBarItemClick(int position) {
        switch (position) {
        case 0:
            addInterest();
            break;
        }
    }
    
    /**
     * add interest
     */
    private void addInterest() {
        isReloadData = true;
        Intent intent = new Intent(this, InterestSelectOneActivity.class);
        startActivity(intent);
    }

    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, final long id) {
        if (parent.getId() == R.id.interestListView) {
            String[] items = new String[]{getString(R.string.delete)};
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setItems(items, new OnClickListener() {
                
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        deleteInterest((int)id);
                    }
                }
            });
            builder.setNegativeButton(getString(R.string.cancel), null);
            builder.show();
        }
        return false;
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //传递参数的名称
        String name = null;
        switch (parent.getId()) {
        case R.id.schoolListView:
            name = "sid";
            break;
        case R.id.interestListView:
            name = "iid";
            break;
        }
        
        if (name != null) {
            Intent intent = new Intent(this, MyListTabActivity.class);
            intent.putExtra(name, (int)id);
            startActivity(intent);
        }
    }
    
    /**
     * delete interest 
     * @param iid
     */
    private void deleteInterest(int iid) {
        List<BasicNameValuePair> params = OAuth.createAuthParams();
        params.add(new BasicNameValuePair("iid", Integer.toString(iid)));
        
        mAsyncRequest.fetch(URL_DELETE, params, new FetchListener() {
            
            public void onError(int code, String msg) {

            }
            
            public void onComplete(JSONObject response) {
                //reload data
                fetchData();
                displayToast(getString(R.string.toast_delete_success));
            }
        });
    }
}
